import tcpServer from '../dxmodules/dxTcpServer.js'
import std from '../dxmodules/dxStd.js'
import logger from '../dxmodules/dxLogger.js'

// id
const id = "tcpServer"

// Initialize TCP service
logger.info(tcpServer.init(6008, 1000, id));

let timer = std.setInterval(() => {
    let clients = JSON.parse(tcpServer.scan(id))
    if (clients && clients.length > 0) {
        logger.info("First client ID detected: ", clients[0].id)
        logger.info("The first client IP detected: ", clients[0].ip)
        logger.info("The first client port detected: ", clients[0].port)
        std.clearInterval(timer)
    }
}, 1000)

std.setInterval(() => {
    if (!tcpServer.msgIsEmpty()) {
        // Data reception
        let msgOjb = tcpServer.msgReceive();
        let data = String.fromCharCode.apply(null, new Uint8Array(msgOjb.data));
        logger.info(data);
        // Data transmission
        let buffer = new ArrayBuffer(4); // Create a buffer of length 4.
        let view = new Uint8Array(buffer);
        // Let's write "abcd"
        view[0] = 0x61;
        view[1] = 0x62;
        view[2] = 0x63;
        view[3] = 0x64;
        logger.info(tcpServer.send(msgOjb.clientId, buffer));
    }
}, 10)
